package com.shopping.controller;

import com.shopping.bean.Administrator;
import com.shopping.bean.User;
import com.shopping.service.IShoppingLoginService;
import com.shopping.util.LayData;
import com.shopping.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    IShoppingLoginService loginService;

    @RequestMapping("shopping/dologin")
    @ResponseBody
    public LayData shoppingLogin(User user, HttpSession session){
//执行登录业务
        User u=loginService.dologin(user);
        //记录登录状态
        if (u != null) {
            // 登录成功，记录登录状态
            System.out.println("从会话中获取的用户 userid: " + u.getUserid());
            session.setAttribute(SYS.SHOPPING_LOGIN_USER, u);
            return LayData.success(200, "登陆成功");
        } else {
            // 登录失败，返回错误信息
            return LayData.success(401, "用户名或密码错误");
        }
    }


    @RequestMapping("system/dologin")
    @ResponseBody
    public LayData systemLogin(Administrator administrator, HttpSession session){
        Administrator admin=loginService.systemlogin(administrator);
        if (admin!=null){
            session.setAttribute(SYS.SYSTEM_LOGIN_ADMIN,admin);
            return LayData.success(200,"登陆成功");
        }else {
            return LayData.success(401,"用户名或密码错误");
        }
    }

    @RequestMapping("logout")
    @ResponseBody
    public LayData logout(HttpSession session) {
        // 清除购物用户的登录信息
        session.removeAttribute(SYS.SHOPPING_LOGIN_USER);
        // 清除管理员的登录信息
        session.removeAttribute(SYS.SYSTEM_LOGIN_ADMIN);
        // 使会话失效
        session.invalidate();
        return LayData.success(200, "退出登录成功");
    }
}
